import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'  // 默认重定向到登录页面
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      name: 'Manager',
      component: () => import('@/views/Manager.vue'),
      redirect: '/home',
      meta: { requiresAuth: true },
      children: [
        { path: 'home', name: 'Home', component: () => import('@/views/manager/Home.vue'), meta: { requiresAuth: true }},
        { path: 'ProductCategory', name: 'ProductCategory', component: () => import('@/views/manager/ProductCategory.vue'), meta: { requiresAuth: true }},
        { path: 'ProductInfo', name: 'ProductInfo', component: () => import('@/views/manager/ProductInfo.vue'), meta: { requiresAuth: true }},
        { path: 'OrderMaster', name: 'OrderMaster', component: () => import('@/views/manager/OrderMaster.vue'), meta: { requiresAuth: true }},
        { path: 'password', name: 'Password', component: () => import('@/views/manager/Password.vue'), meta: { requiresAuth: true }},
        { path: 'login-log', name: 'LoginLog', component: () => import('@/views/manager/LoginLog.vue'), meta: { requiresAuth: true }},
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: {
        // 不需要登录就能访问的页面
        requiresAuth: false
      }
    }
  ]
})

// 路由守卫
router.beforeEach(to => {
  // 直接放行的路由 如:登录
  if (to.name === 'Login') {
    return true;
  }
  // 如果没有登录不允许路由到主界面home
  // 统一登录身份认证,  在没有登录的情况不允许进入需要登录身份认证的页面
  // 具体实现方式: 登录成功后保存token,  在全局前置导航守卫处统一判断
  const token = localStorage.getItem('token')
  if (token) {
    return true // 放行
  } else {
    return { path: '/login' } //重定向到/路由登录界面
  }
})

export default router
